package com.linln.wtp.config;

import com.linln.common.enums.OrderEnum;
import com.linln.modules.order.domain.YearauditOrder;
import com.linln.modules.order.service.YearauditOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 监听 Redis key 过期事件
 *
 * @Author Lizhou
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {


    @Autowired
    YearauditOrderService yearauditOrderService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer redisMessageListenerContainer) {
        super(redisMessageListenerContainer);
    }

    /**
     * 针对 redis 数据失效事件，进行数据处理
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 拿到key
        String channel = new String(message.getChannel(), StandardCharsets.UTF_8);
        //过期的key
        String key = new String(message.getBody(), StandardCharsets.UTF_8);
        //待支付订单改变状态
        closeOrder(key);

        log.info("redis key 过期：pattern={},channel={},key={}", new String(pattern), channel, key);
    }

    /**
     * 关闭待支付订单
     * @param key
     */
    private void closeOrder(String key) {
        if(key.contains(OrderEnum.WAITPAY.name())){
            String msg = "";
            boolean flag = false;
            String[] keys = key.split("-");
            if(keys.length>1){
                String orderId = keys[1];
                YearauditOrder yearauditOrder = yearauditOrderService.getById(orderId);
                if(yearauditOrder == null){
                    msg = "错误：订单"+keys[1]+"不存在";
                    flag = true;
                }else {
                    yearauditOrder.setStatus(OrderEnum.CANCEL.getCode());
                    yearauditOrderService.updateById(yearauditOrder);
                }
            }else {
                msg = "错误：无订单";
                flag = true;
            }
            if(flag){
                log.error(msg);
            }
        }
    }
}